import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:xiandou/Common.dart';
import 'package:xiandou/Request/DioManager.dart';
import 'package:xiandou/Request/NWApi.dart';
import 'package:xiandou/Request/NWMethod.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:xiandou/common/XDAlertView.dart';
import 'package:xiandou/Views/UploadProof.dart';
import 'package:xiandou/home/SubmitOrderController.dart';
import 'package:xiandou/models/Index.dart';


class TaskDetailPage extends StatefulWidget {
  @override
  int taskId =0;
  TaskDetailPage({Key key, @required this.taskId})
      : super(key:key);
  _TaskDetailPageState createState() => _TaskDetailPageState();
}

class _TaskDetailPageState extends State<TaskDetailPage> {

  TaskDetailsModel taskDetailModel =new TaskDetailsModel();

  @override
  void initState() {
    super.initState();
    _requestTaskDetail();
  }

  void _requestTaskDetail() {
    var params ={'taskId':widget.taskId};
    DioManager().request(NWMethod.GET, NWApi.getTaskDetailApi,params: params,success: (data){
      print(data);
      setState(() {
        taskDetailModel = TaskDetailsModel.fromJson(data);
      });
    },error: (error){
      Fluttertoast.showToast(msg: error.message);
    });
  }

  void _requestGiveUpTask() {
    var params = {'taskId':widget.taskId};
    DioManager().request(NWMethod.GET, NWApi.orderGiveupApi,params: params,success: (data){
      print(data);
      Fluttertoast.showToast(msg: '放弃任务成功');
      _requestTaskDetail();
    },error: (errer){
      Fluttertoast.showToast(msg: errer.message);
    });
  }

  void _requestTaskStart() {
    Map<String,dynamic> params = {'taskId':widget.taskId.toString()};
    DioManager().request(NWMethod.GET, NWApi.TaskStartApi,params: params,success: (data){
      Fluttertoast.showToast(msg: '参与成功');
      _requestTaskDetail();
    },error: (error){
      if(error.code == 202010){
        YYAlertDialogWithDivider(context,'当前还没有绑定个人id，要先去绑定吗？',(){
          Future.delayed(Duration(milliseconds: 50), (){
            Navigator.push(
              context,
              new MaterialPageRoute(builder: (context) => new UploadProofScreen(taskCategoryId: taskDetailModel.taskCategoryId.toString(),)),
            );
          });
      },(){
        });
      }else{
        Fluttertoast.showToast(msg: error.message);
      }
    });
  }

  Widget orderErrorStatusWidget(String errorString) {
    return Container(
      height: 54,
      padding: const EdgeInsets.only(bottom: 0),
      child:
          Container(
            color:Color(0xffF4EDEB),
            height: 54,
            width: MediaQuery.of(context).size.width,
            child: FlatButton(
              child: Text(errorString),
            ),
          ),
    );
  }

  Widget ongoingStatusWidget(String titleString) {
    return Row(
      children: <Widget>[
        Container(
          color:Color(0xffF4EDEB),
          height: 54,
          width: MediaQuery.of(context).size.width/2,
          child: FlatButton(
            child: Text('放弃任务'),
            onPressed: _requestGiveUpTask,
          ),
        ),
        Container(
          color:Color(0xffFF5236),
          height: 54,
          width: MediaQuery.of(context).size.width/2,
          child: FlatButton(
            child: Text(titleString,style: TextStyle(color: Colors.white),),
            onPressed: (){
              Navigator.push(
                  context,
                  new MaterialPageRoute(builder: (context) => new OrderSubmitPage(taskDetailModel: taskDetailModel,))
              ).then((value) => {
                _requestTaskDetail()
              });
            },
          ),
        ),
      ],
    );
  }

  Widget orderButtonWidget(int taskStatus) {
    if(taskStatus == -2 || taskStatus == -1) {
      return Container(
            height: 54,
            width: MediaQuery.of(context).size.width,
            padding: const EdgeInsets.all(0),
            color: Color(0xffFF5236),
            child: FlatButton(
              child: Text('开始任务',style: TextStyle(color: Colors.white),),
              onPressed:_requestTaskStart,
            ),
          );
//        Row(
//        children: <Widget>[
//          Container(
//            color:Color(0xffF4EDEB),
//            height: 54,
//            width: MediaQuery.of(context).size.width/2,
//            child: FlatButton(
//              child: Text('放弃任务'),
//              onPressed: _requestGiveUpTask,
//            ),
//          ),
//          Container(
//            height: 54,
//            width: MediaQuery.of(context).size.width - MediaQuery.of(context).size.width/2,
//            padding: const EdgeInsets.all(0),
//            color: Color(0xffFF5236),
//            child: FlatButton(
//              child: Text('开始任务',style: TextStyle(color: Colors.white),),
//              onPressed:_requestTaskStart,
//            ),
//          )
//        ],
//      );
    }else if(taskStatus == 1){
      return orderErrorStatusWidget('已完成任务，正在审核');
    }else if(taskStatus == 2){
      return orderErrorStatusWidget('该任务您已完成，去看看其他任务吧');
    }else if(taskStatus == 0){
      return ongoingStatusWidget('已领取任务，继续完成');
    } else {
      return Container();
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build

    return Scaffold(
        appBar: CupertinoNavigationBar(
          backgroundColor: Colors.white,
          middle: const Text('任务详情'),
        ),
        body:Column(
          children: <Widget>[
            Expanded(
              child: ListView(
                children: <Widget>[
                  Container(
                    alignment: Alignment.topLeft,
                    padding: const EdgeInsets.only(left: 21,top: 30),
                    child: Text(taskDetailModel.taskTitle,style: TextStyle(fontSize: 25,fontWeight: FontWeight.bold),),
                  ),
                  Container(
                    padding: const EdgeInsets.only(left: 21,top: 16,right: 21),
                    child: Row(
                      children: <Widget>[
                        Text.rich(TextSpan(
                          children: [
                            TextSpan(text: '当前参与人数',style: TextStyle(color: Common.darkColor,fontSize: 15,fontWeight: FontWeight.w500)),
                            TextSpan(text: taskDetailModel.taskAttendanceNumber.toString()+'       ',style: TextStyle(color: Common.xdDeepRedColor,fontSize: 15,fontWeight: FontWeight.bold)),
                          ]
                        )),
                        Text.rich(TextSpan(
                            children: [
                              TextSpan(text: '累计参与人数',style: TextStyle(color: Common.darkColor,fontSize: 15,fontWeight: FontWeight.w500)),
                              TextSpan(text: taskDetailModel.taskMaxJoinNumber.toString(),style: TextStyle(color: Common.xdDeepRedColor,fontSize: 15,fontWeight: FontWeight.bold)),
                            ]
                        ))
                      ],
                    ),
                  ),
                  Container(
                      height: 100,
                      margin: const EdgeInsets.only(top: 10),
                      child:Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Expanded(
                            child:Column(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: <Widget>[
                                Text('任务红包奖励',style: TextStyle(color: Color(0xff666666),fontSize: 15,fontWeight: FontWeight.w500),),
                                Text(taskDetailModel.award.toString(),style: TextStyle(color: Color(0xffFFBD18),fontSize: 20,fontWeight: FontWeight.bold)),
                              ],
                            ),
                            flex: 1,
                          ),
                          Expanded(
                            child:Column(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: <Widget>[
                                Text('截止时间',style: TextStyle(color: Color(0xff666666),fontSize: 15,fontWeight: FontWeight.w500)),
                                Text(taskDetailModel.endTime,style: TextStyle(color: Color(0xff333333),fontSize: 17,fontWeight: FontWeight.bold)),
                              ],
                            ),
                            flex: 1,
                          ),
                        ],
                      )
                  ),
                  Container(
                    height: 1,
                    margin: const EdgeInsets.only(left: 10,right: 10),
                    decoration: new BoxDecoration(
                      color: Color(0xffEEEEEE),
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.only(left: 20,top: 30,bottom: 35,right: 20),
                    alignment: Alignment.topLeft,
                    child: Column(
                      crossAxisAlignment:CrossAxisAlignment.stretch,
                      children: <Widget>[
                        Text('任务规则',style: TextStyle(color: Color(0xff666666),fontSize: 15,fontWeight: FontWeight.w500)),
                        Text('一、任务时间',style: TextStyle(color: Color(0xff333333),fontSize: 17,fontWeight: FontWeight.bold)),
                        Text.rich(TextSpan(
                            children: [
                              TextSpan(text: '本任务分期开展，任务时间将通过任务规则等方式进行公告，本期任务时间为',style: TextStyle(color: Color(0xff666666),fontSize: 16,fontWeight: FontWeight.w500)),
                              TextSpan(text: '2020年9月30日',style: TextStyle(color: Color(0xffFF5236),fontSize: 16,fontWeight: FontWeight.bold)),
                            ]
                        )),
                        Text('二、任务描述',style: TextStyle(color: Color(0xff333333),fontSize: 17,fontWeight: FontWeight.bold)),
                        Text.rich(TextSpan(
                            children: [
                              TextSpan(text: '（1）参与赚赏金的用户可以通过二维码的途径邀请其他支付宝用户，活动仅限支付宝实名用户使用10.1.24版本以上客户端参与；（2）如果被邀请的用户从未开通过任一电子公交卡（码）也从未开通过任何公交官方APP刷码乘车支付宝支付渠道的用户，在领取优惠之时起7*24小时内，首次开通活动指定电子公交卡（码）或指定公交官方APP刷码乘车支付渠道，即视为完成1次任务，1次任务完成仅可获得1次赏金，赏金为0.5元（人民币）。',style: TextStyle(color: Color(0xff666666),fontSize: 16,fontWeight: FontWeight.w500)),
                              TextSpan(text: taskDetailModel.taskDescription,style: TextStyle(color: Color(0xffFF5236),fontSize: 16,fontWeight: FontWeight.bold)),
                            ]
                        )),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Container(
              height: 54,
              padding: const EdgeInsets.only(bottom: 0),
              child: orderButtonWidget(taskDetailModel.taskStatus),
            ),
          ],
        )
    );
  }
}